import type { CardInfoData, CardCustomAttrItem } from '/@/api/general/model/cardModel';
import type { GoodWeChatUrlParams } from '/@/api/model/commonModel';
import { SearchMapValTypeEnum } from '/@/api/general/model/cardModel';
import { defineComponent, reactive, ref, unref } from 'vue';
import setting from '/@/settings/projectSetting';
import { useGo } from '/@/hooks/web/usePage';
import { useVModels } from '@vueuse/core';
import { useCurrentDeckStore } from '/@/store/modules/currentDeck';
import { aTabClick, awaitWrap } from '/@/utils';
import { CardDetailApi } from '/@/api/general/card';
import { GoodWeChatUrlApi } from '/@/api/common';
import { isArray, isObject, isWeChatBrowser } from '/@/utils/is';
import { sharePageOpenApp } from '/@/utils/appInteractive';
import { Popup } from 'vant';
import { Icon } from '/@/components/Icon';

import('./DeckCardDetailPopup.less');

export default defineComponent({
  name: 'DeckCardDetailPopup',
  props: {
    show: {
      type: Boolean as PropType<boolean>,
      required: true,
      default: () => {
        return false;
      },
    },
    cardId: {
      type: Number as PropType<number>,
      required: true,
    },
  },
  setup(props, { emit }) {
    const go = useGo();

    const { show } = useVModels(props, emit);

    const currentStore = useCurrentDeckStore();

    const detailLoding = ref(true);
    const detailData = reactive<{ current: CardInfoData }>({
      current: {} as CardInfoData,
    });

    const getLinkCard = async () => {
      const { cardId } = props;
      detailData.current = {} as CardInfoData;
      const [error, data] = await awaitWrap(CardDetailApi({ game_id: currentStore.gameId, id: cardId }));
      if (error || !data) {
        return false;
      }
      detailData.current = data as CardInfoData;
      detailLoding.value = false;
    };

    // 跳转到APP或者小程序
    const goToBuyClick = async () => {
      const { shopping, card_fixed_attr } = detailData.current;
      const { card } = card_fixed_attr;
      if (isWeChatBrowser()) {
        const params: GoodWeChatUrlParams = {
          type: 'tool_card',
          good_id: {
            card_no: card.card_no,
            rarity: card.rarity!,
          },
          game_id: currentStore.getDeckConfig.trade_game_id,
        };
        const [error, data] = await awaitWrap(GoodWeChatUrlApi(params));
        if (error || !data) {
          aTabClick(setting.wechatAppHomeUrl, '_blank');
          return;
        }
        aTabClick(data.url_link, '_blank');
        return;
      }

      shopping.link_url ? sharePageOpenApp(shopping.link_url) : null;
    };

    const CustomCardAttrs = ({ customAttrs }: { customAttrs: CardCustomAttrItem[] }) => {
      if (!isArray(customAttrs)) {
        return null;
      }
      const AttrsArray: VueNode[] = [];
      for (const item of customAttrs) {
        if (item.style === SearchMapValTypeEnum.IMAGE) {
          const { imgs } = item;
          imgs.length
            ? AttrsArray.push(
                <div class='flex text-sm'>
                  <span>{item.title}</span>：
                  <div class={'flex flex-1 flex-wrap'}>
                    {imgs.map((src) => {
                      return <img src={src} alt='' class={'h-36px mr-sm mb-sm'} />;
                    })}
                  </div>
                </div>
              )
            : null;
        } else {
          const { text } = item;
          text
            ? AttrsArray.push(
                <div class='flex text-sm'>
                  <span>{item.title}：</span>
                  <span class={['flex-1 whitespace-pre-line']}>{text}</span>
                </div>
              )
            : null;
        }
      }
      return <>{AttrsArray}</>;
    };

    const CardDetail = () => {
      if (unref(detailLoding)) {
        return null;
      }
      const { is_show_ename, is_show_card_no } = currentStore.getDeckConfig;
      const { card_fixed_attr, card_custom_attrs } = detailData.current;
      const { card, series } = card_fixed_attr;
      const { up, down } = card_custom_attrs;

      const OtherVersionBox = () => {
        const { other_version } = detailData.current;
        if (!other_version || !other_version.length) {
          return null;
        }
        return (
          <div class='deck-other-box mt-md'>
            <div class={'text-gray-400 text-sm'}>其他版本</div>
            <ul class={'ver-list text-black'}>
              {other_version.map((item) => {
                const verPrice = item.price ? item.price / 100 : 0;
                return (
                  <li
                    class={'text-sm py-10px flex justify-between'}
                    onClick={() => {
                      go(`/generalcard/${currentStore.gameId}/${item.id}`);
                    }}
                  >
                    <div class={'w-[82%] van-ellipsis'}>
                      <span class={'mr-sm'}>{item.series_name}</span>
                      <span class={'mr-sm'}>{item.series_abbr}</span>
                      <span>[{item.sindex}]</span>
                    </div>
                    {verPrice ? <div class={'text-red-500'}>¥{verPrice}</div> : null}
                  </li>
                );
              })}
            </ul>
          </div>
        );
      };

      const OtherLinkBox = () => {
        const { other_card_link_list, other_card_link_title } = detailData.current;
        if (!other_card_link_list || !other_card_link_list.length) {
          return null;
        }
        return (
          <div class='deck-other-box mt-md'>
            <div class={'text-gray-400 text-sm'}>{other_card_link_title}</div>
            <ul class={'ver-list text-black'}>
              {other_card_link_list.map((item) => {
                const verPrice = item.price ? item.price / 100 : 0;
                return (
                  <li
                    class={'text-sm py-10px flex justify-between'}
                    onClick={() => {
                      go(`/generalcard/${currentStore.gameId}/${item.id}`);
                    }}
                  >
                    <div class={'w-[82%] van-ellipsis'}>
                      <span class={'mr-sm'}>{item.series_name}</span>
                      <span class={'mr-sm'}>{item.series_abbr}</span>
                      <span>[{item.sindex}]</span>
                    </div>
                    {verPrice ? <div class={'text-red-500'}>¥{verPrice}</div> : null}
                  </li>
                );
              })}
            </ul>
          </div>
        );
      };

      return (
        <div class={'card-detail-container text-gray-500'}>
          <div class={'image-area mx-auto'}>
            <img class={'mx-auto'} src={card.img} alt='' />
          </div>
          <div class={'card-name text-base font-bold mt-lg text-black'}>{card.name}</div>
          {is_show_ename ? <div class={'card-ename text-sm'}>{card.ename}</div> : null}
          {is_show_card_no ? <div class={'card-ename text-sm'}>{card.card_no}</div> : null}
          <div class='my-md bg-gradient-to-r from-white via-gray-400/30 to-white w-full h-1px'></div>
          <li class='flex text-sm'>
            <span>系列：</span>
            <span class={['flex-1 whitespace-pre-line']}>{series.name}</span>
          </li>
          <CustomCardAttrs customAttrs={up} />
          <CustomCardAttrs customAttrs={down} />
          <OtherLinkBox />
          <OtherVersionBox />
        </div>
      );
    };

    const Mall = () => {
      if (unref(detailLoding)) {
        return null;
      }
      const { shopping } = detailData.current;
      if (!isObject(shopping)) {
        return null;
      }
      return (
        <div class={'mall flex justify-center'}>
          {Number(shopping.min_price) ? (
            <ul class={'price flex items-center'}>
              <li>最低价</li>
              <li class={'nums'}>
                <span>¥</span>
                {shopping.min_price / 100}
              </li>
            </ul>
          ) : null}
          <div class={'shop-car text-base text-blue-500 flex items-center'} onClick={goToBuyClick}>
            <Icon class={'!text-lg'} icon={'material-symbols:shopping-cart-rounded'} />
            <span>前去购买</span>
          </div>
        </div>
      );
    };

    return () => (
      <Popup
        v-model={[show.value, 'show']}
        class={'current-deck-card-detail-popup'}
        teleport={'body'}
        round={false}
        onOpen={getLinkCard}
        onClose={() => {
          detailLoding.value = true;
        }}
        closeOnClickOverlay
      >
        <CardDetail />
        <Mall />
      </Popup>
    );
  },
});
